package com.qfedu.fmmall.service.impl;

import com.qfedu.fmmall.dao.ProductCommentsMapper;
import com.qfedu.fmmall.entity.ProductComments;
import com.qfedu.fmmall.entity.ProductCommentsVo;
import com.qfedu.fmmall.service.ProductCommentsService;
import com.qfedu.fmmall.utils.PageHelper;
import com.qfedu.fmmall.vo.ResultStatus;
import com.qfedu.fmmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;

@Service
public class ProductCommentsServiceImpl implements ProductCommentsService{

    @Autowired
    private ProductCommentsMapper productCommentsMapper;

    @Override
    public ResultVo CommontsByProductId(String productId,int pageNum,int limit) {
        //根据id查询总记录数
        Example example = new Example(ProductComments.class);
        Example.Criteria criteria = example.createCriteria();
         criteria.andEqualTo("productId", productId);
        int count = productCommentsMapper.selectCountByExample(example);

        //计算总页数（必须确定每页显示多少条 pageSize = limit）
        int pageCOunt = count%limit==0? count/limit : count/limit+1;

        //查询当前页的数据（因为评论中需要用户信息，因为需要连表查询---自定义）
        int start = (pageNum-1)*limit;
        List<ProductCommentsVo> list = productCommentsMapper.selectCommontsByProductId(productId, start, limit);

        return  new ResultVo(ResultStatus.OK,"success",new PageHelper<ProductCommentsVo>(count,pageCOunt,list));


    }

    @Override
    public ResultVo getCommontsCountByProductId(String productId) {
        Example example = new Example(ProductComments.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId",productId);
        //获取评论总数
        int total = productCommentsMapper.selectCountByExample(example);

        //获取好评
        int goodTotal = getTotal(productId,1);

        //获取中评
        int mindTotal = getTotal(productId,0);

        //获取差评
        int badTotal = total - goodTotal - mindTotal;

        //好评率
        double percent = (Double.parseDouble(goodTotal+"") / Double.parseDouble(total+""))*100;
        String percentValue = (percent+"").substring(0,(percent+"").lastIndexOf(".")+3);

        HashMap<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("goodTotal",goodTotal);
        map.put("mindTotal",mindTotal);
        map.put("badTotal",badTotal);
        map.put("percentValue",percentValue);

        return new ResultVo(ResultStatus.OK,"Success",map);
    }

    int getTotal(String productId,int type){
        Example example = new Example(ProductComments.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId",productId);
        criteria.andEqualTo("commType",type);
        return  productCommentsMapper.selectCountByExample(example);
    }
}
